#pragma once
#include<iostream>
#include<cstring>
#include<unistd.h>
#include<functional>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<sys/wait.h>    
#include<pthread.h>
#include"Log.hpp"
#include"InetAddr.hpp"

using namespace log_ns;

using command_service_t=std::function<void(int sockfd,InetAddr addr)>;

enum
{
    SOCKET_ERROR=1,
    BAND_ERROR,
    LISTEN_ERROR
};

const static int gport=8888;
const static int gsock=-1;
const static int gblcklog=8;

class TcpServer
{
public:
    TcpServer(command_service_t service,uint16_t port=gport)
        :_port(port)
        ,_listensockfd(gsock)
        ,_isrunning(false)
        ,_service(service)
    {}

    void InitServer()
    {
        //创建
        _listensockfd=::socket(AF_INET,SOCK_STREAM,0);
        if(_listensockfd<0)
        {
            exit(SOCKET_ERROR);
            LOG(FATAL,"socket create error\n");
        }
        LOG(INFO,"socket create sussess,listensockfd: %d\n",_listensockfd); //3

        struct sockaddr_in local;
        memset(&local,0,sizeof(local));

        local.sin_family=AF_INET;
        local.sin_port=htons(_port);  //网络序列
        local.sin_addr.s_addr=INADDR_ANY;
        //绑定：sockfd 和 socket addr
        if(::bind(_listensockfd,(struct sockaddr*)&local,sizeof(local))<0)
        {
            LOG(FATAL,"bind error\n");
            exit(BAND_ERROR);
        }
        LOG(INFO,"bind success\n");

        // 设置监听状态 listen
        if(::listen(_listensockfd,gblcklog)<0)
        {
            LOG(FATAL,"listen error\n");
            exit(LISTEN_ERROR);
        }
        LOG(INFO,"listen success\n");
    }

    class ThreadData
    {
    public:
        int _sockfd;
        TcpServer *_self;
        InetAddr _addr;

    public:
        ThreadData(int sockfd,TcpServer *self,const InetAddr &addr):_sockfd(sockfd),_self(self),_addr(addr)
        {}
    };

    void Loop()
    {
        //signal(SIGCHLD,SIG_IGN);
        _isrunning=true;
        while(_isrunning)
        {
            struct sockaddr_in client;
            socklen_t len=sizeof(client);
            // 获取新连接
            int sockfd=::accept(_listensockfd,(struct sockaddr*)&client,&len);
            if(sockfd<0)
            {
                //获取连接失败
                LOG(WARING,"accept error\n");
                continue;
            }
            InetAddr addr(client);
            LOG(INFO,"get a new link,client info: %s, sockfd is: %d\n",addr.AddrStr().c_str(),sockfd); //4

            //提供服务--version 2(多线程版)
            pthread_t tid;
            ThreadData *td=new ThreadData(sockfd,this,addr);
            pthread_create(&tid,nullptr,Excute,td); //新线程分离

        }

        _isrunning=false;
    }

    static void *Excute(void *argc)
    {
        ThreadData *td=static_cast<ThreadData *>(argc);
        pthread_detach(pthread_self());
        td->_self->_service(td->_sockfd,td->_addr);
        ::close(td->_sockfd);
        delete td;
        return nullptr;
    }

    ~TcpServer()
    {}

private:
    uint16_t _port;
    int _listensockfd;
    bool _isrunning;

    command_service_t _service;
};